
package org.example.baseinfo.service.async;

import jakarta.annotation.Resource;
import org.example.baseinfo.entity.ChangeLogEntity;
import org.example.baseinfo.entity.SchoolEntity;
import org.example.baseinfo.pojo.vo.school.SchoolVO;
import org.example.baseinfo.repository.*;
import org.example.baseinfo.service.IAsyncMqService;
import org.example.baseinfo.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.example.baseinfo.util.JsonUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class AsyncMqService implements IAsyncMqService {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private ISchoolRepository organizationRepository;

    @Resource
    private IChangeLogRepository changeLogRepository;

    private static final String ORGAN_EXCHANGE = "baseInfo.school.exchange";




    @Override
    @Async("taskAsyncPool")
    public void sendSchoolInfoMessage(String schoolCode) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 查询业务编码
        SchoolEntity schoolEntity = organizationRepository.findByDeleteStatusAndSchoolCode(Short.valueOf("1"),schoolCode);
        if (schoolEntity == null) {
            log.warn("学校业务通知 - 未查询到学校信息 - schoolCode:{}", schoolCode);
            return;
        }
        SchoolVO vo = new SchoolVO();
        BeanUtils.copyProperties(schoolEntity,vo);

        String routingKey = "school_base_change";
        rabbitTemplate.convertAndSend(ORGAN_EXCHANGE, routingKey,
                JsonUtil.convertObject(vo));
    }

    @Override
    @Async("taskAsyncPool")
    public void saveSchoolChangeLog(SchoolEntity entity, String user, String source) {
        SchoolEntity oldInfo = organizationRepository.findByIdAndDeleteStatus(entity.getSchoolId(),Short.valueOf("1"));
        ChangeLogEntity changeLogEntity = new ChangeLogEntity();
        changeLogEntity.setChangeDate(DateUtils.getCurrentDateToString());
        changeLogEntity.setChangeUser(user);
        changeLogEntity.setSource(source);
        changeLogEntity.setSchoolId(entity.getSchoolId());
        changeLogEntity.setDetail(JsonUtil.convertObject(entity.toString()));
        changeLogEntity.setDetailOld(JsonUtil.convertObject(oldInfo.toString()));
        changeLogRepository.save(changeLogEntity);
    }
}
